<?php

namespace App;

use http\Env\Request;
use Illuminate\Notifications\Notifiable;


class User extends Base
{
    use Notifiable;



    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function Login($map)
    {

        //查找是否存在该用户
        $model = self::getone($map['openid']);

        if($model->isEmpty()){
            //如果不存在就创建用户
            $rew = self::create($map);
            //返回Token
            $token = Token::create(['uid'=>$rew['id'],'token'=>md5(time().rand(10000,99999))]);
            return $token;
        }else{

            //更新用户表
            $rew = self::where('openid',$map['openid'])->update($map);
            //更新token
            $token = Token::where('uid',$model[0]['id'])->update([
                'token'=>md5(time().rand(10000,99999)),
                'updated_at'=>date('Y-m-d H:i:s',time())
            ]);
            if($token){
                //查找token
                $model = Token::where('uid',$model[0]['id'])->first();
            }else{
                //新建
                $dat['uid'] = $model[0]['id'];
                $dat['token'] = md5(time().rand(10000,99999));
                $model = Token::create($dat);

            }
            return $model;
        }

    }


    /**
     * 获取用户信息
     * @param $openid
     * @return mixed
     */
    public static function getone($openid)
    {
        $model = self::where('openid',$openid)->get();
        return $model ;
    }

}
